package com.cwits.wifi.ui.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.text.TextUtils;

import com.cwits.cyx_drive_sdk.dvr.DVRCSVUtil;
import com.cwits.cyx_drive_sdk.dvr.OnDownloadFTPFileListener;
import com.cwits.wifi.MainApplication;
import com.cwits.wifi.dvr.DVRCarManager;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.tool.WifiHelper;
import com.cwits.wifi.util.AppUtil;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.IConstant;
import com.cwits.wifi.util.PreferencesHelper;
import com.jieli.lib.stream.tools.CommandHub;
import com.jieli.lib.stream.util.ICommon;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * Created by ZhangHua on 2016-06-24.
 * 后台服务处理，在停车的时候连接设备wifi，获取设备数据，之后上传到后台
 */
public class BackgroundGetDeviceDataService extends Service implements IConstant,IAction,ICommon{
    String tag = this.getClass().getSimpleName();
    private SensorManager mSensorManager;//传感器管理类
    private MySensorEventListener mySensorEventListener; // 传感器监听器
    public MainApplication mApplication;
    private WifiHelper mWifiHelper;//wifi管理类
    private boolean isIniting = false;
    private static boolean isGetingDeviceData = false;
    private PowerManager.WakeLock wake_lock;
    private Handler mHandler;
    private String mSensorPathStr;

    private List<Double> mXYZData = new ArrayList<Double>();

    public BackgroundGetDeviceDataService() {
    }

    @Override
    public  void onCreate(){
        super.onCreate();
        Dbug.i(tag, "------------onCreate-----------");
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wake_lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag);
        wake_lock.acquire();
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mySensorEventListener = new MySensorEventListener();
        mSensorManager.registerListener(mySensorEventListener,mSensorManager
                .getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),SensorManager.SENSOR_DELAY_UI);
        mApplication = (MainApplication) getApplication();
        mWifiHelper = WifiHelper.getInstance(getApplicationContext());
        mHandler = new Handler();
        isGetingDeviceData = false;
        mSensorPathStr = Environment.getExternalStorageDirectory()
                .getAbsolutePath()
                + "/lipeibao/"
                + format("yyyyMMddHHmmss") + "sensor.txt";
        Dbug.i(tag, "------------FilePath:-----------" + mSensorPathStr);
        //createFile(mSensorPathStr);
        registerReceiver();
    }

    /**
     * 获得当前时间的格式化输出
     *
     * @param format
     *            格式
     * @return 返回日期字符串
     */
    public static String format(String format) {
        String str = null;
        ;
        try {
            if (format != null) {
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
                str = sdf.format(calendar.getTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static void createFile(String path) {
        File f = new File(path);
        if (!f.exists())
            try {
                f.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    public static void writeDataToFile(String fileName, String message) {


		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(fileName, true)));
			out.write(message + "\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(out != null)
				{
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Dbug.i(tag, "------------onStartCommand-----------");
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        Dbug.i(tag, "onDestroy=============");
        if (null != wake_lock && wake_lock.isHeld()) {
            wake_lock.release();
        }
        if(mySensorEventListener != null&& mSensorManager != null){
            mSensorManager.unregisterListener(mySensorEventListener,mSensorManager
                    .getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION));
        }

        super.onDestroy();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Dbug.w(tag, "onTaskRemoved=============");
        stopSelf();
        super.onTaskRemoved(rootIntent);
    }


    /**
     * 传感器监听器
     *
     * @author Administrator
     *
     */
    private class MySensorEventListener implements SensorEventListener {
        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            // LogUtil.printLog(LogUtil.DEBUG, TAG, "MySensorEventListener");
            switch (event.sensor.getType()) {
                case Sensor.TYPE_GYROSCOPE: // 陀螺仪
                    break;
                case Sensor.TYPE_LINEAR_ACCELERATION:
                case Sensor.TYPE_ACCELEROMETER:
                    double x = event.values[0];
                    double y = event.values[1];
                    double z = event.values[2];
                    double xyz = Math.sqrt(x*x + y*y + z*z);
                    //Dbug.i(tag,"-------------xyz:" + xyz);
                    if(isIniting == true)
                        return;
                    if(mXYZData.size() >= 5){
                        //判断是否是汽车启动
                        judgeSensorData();
                        mXYZData.clear();
                        mXYZData.add(xyz);
                    }else{
                        mXYZData.add(xyz);
                    }
                    break;
                case Sensor.TYPE_GRAVITY:
                    break;
                case Sensor.TYPE_ORIENTATION:
                    break;
                case Sensor.TYPE_LIGHT:
                    break;
                case Sensor.TYPE_MAGNETIC_FIELD:
                    break;
                case Sensor.TYPE_PRESSURE:
                    break;
                case Sensor.TYPE_TEMPERATURE:
                    break;
                case Sensor.TYPE_ROTATION_VECTOR:
                    break;
                case Sensor.TYPE_PROXIMITY:
                    break;
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

    /**
     * 判断是否开车启动
     */
    private void judgeSensorData(){
        boolean isNeedGetData = true;
        //判断是否需要更新
        for(int i = 0;i < (mXYZData.size() - 1);i++){
            if(mXYZData.get(i) < 2 ||mXYZData.get(i + 1) < 2||(mXYZData.get(i) < (mXYZData.get(i + 1) - 2)))
                isNeedGetData = false;
        }
        if(!AppUtil.isAppInBackground(this)){
            //app正在运行
            if(isNeedGetData)
                connnectToGetDeviceData_noBackground();
        }else{
            //需要更新就去联网获取设备数据
            if(isNeedGetData)
                connnectToGetDeviceData_Background();
        }

    }
    /**
     * 向设备要数据
     */
    private void getDevicesData(){
        //处理数据，获取设备数据，获取完成之后断开设备
        String device_id = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("device_id",null);
        if(device_id == null)
            return;
        DVRCarManager.getInstance().initRegisterInfo(device_id, "chainway", this.getApplicationContext());
        if(isGetingDeviceData)
            return;
        if(AppUtil.isAppInBackground(this)){
            isGetingDeviceData = true;
            DVRCarManager.getInstance().setIsDownloading(true);
            DVRCarManager.getInstance().downloadFTPFiles("192.168.1.1", 21, "FTPX", "12345678", device_id, new OnDownloadFTPFileListener() {
                @Override
                public void onDownloadInit(int errorcode, boolean issuccess) {
                    if (!issuccess) {
                        isGetingDeviceData = false;
                        DVRCarManager.getInstance().setIsDownloading(false);
                        disconnectDevice();
                    }
                    Dbug.i(tag, "-------------onDownloadInit-----");
                }

                @Override
                public void onDownloadAllSuccess(int i) {
                    Dbug.i(tag, "-------------onDownloadAllSuccess-----");
                    DVRCarManager.getInstance().setIsDownloading(false);
                    PreferencesHelper.putLongValue(BackgroundGetDeviceDataService.this.getApplicationContext(),"download_cardev_time",System.currentTimeMillis());
                    if (!AppUtil.isAppInBackground(BackgroundGetDeviceDataService.this)) {
                        isGetingDeviceData = false;
                    } else {
                        disconnectDevice();
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                uploadData();
                            }
                        }, 4000);
                    }

                }

                @Override
                public void onDownloadFinish() {
                    DVRCarManager.getInstance().setIsDownloading(false);
                    DVRCarManager.getInstance().sendFinishDownloadBroadcast(BackgroundGetDeviceDataService.this.getApplicationContext());
                    if (!AppUtil.isAppInBackground(BackgroundGetDeviceDataService.this)) {
                        isGetingDeviceData = false;
                    }
                }

                @Override
                public void onDownloadFailed(int i, int i1, int i2) {
                    Dbug.i(tag, "-------------onDownloadFailed-----");
                }

                @Override
                public void onDownloadPrograss(String s, int i, int i1) {
                    Dbug.i(tag, "-------------onDownloadPrograss----filename:" + s + "----count:" + i + "----index:" + i1);
                }
            });

        }else{
            //do nothing
        }
    }

    private void uploadData(){
        String device_id = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("device_id",null);
        if(device_id == null)
            return;
        //DVRManager.getInstance().initRegisterInfo(device_id,"chainway",this.getApplicationContext());
        DVRCarManager.getInstance().setIsUploading(true);
        DVRCarManager.getInstance().uploadHTTPFiles(new DVRCSVUtil.OnUploadStrokeListener() {
            @Override
            public void onUploadInit(int errorcode, boolean is_success) {
                Dbug.i(tag, "-------------onUploadInit-----issuccess:" + is_success);
                if(!is_success){
                    isGetingDeviceData = false;
                    DVRCarManager.getInstance().setIsUploading(false);
                }
            }

            @Override
            public void onUploadFailed(int i, String filename,int i1, int i2) {
                Dbug.i(tag,"-------------onUploadFailed-----errorcode:" + i);
            }

            @Override
            public void onUploadPrograss(String s, int i, int i1) {
                Dbug.i(tag,"-------------onUploadPrograss----filename:" + s + "----count:" + i + "----index:" + i1);
            }

            @Override
            public void onUploadAllSuccess(int i) {
                Dbug.i(tag,"-------------onUploadAllSuccess-----");
                isGetingDeviceData = false;
                DVRCarManager.getInstance().setIsUploading(false);
                PreferencesHelper.putLongValue(BackgroundGetDeviceDataService.this.getApplicationContext(), "upload_cardev_time", System.currentTimeMillis());
            }

            @Override
            public void onUploadFinish() {
                isGetingDeviceData = false;
                DVRCarManager.getInstance().setIsUploading(false);
                DVRCarManager.getInstance().sendFinishUploadBroadcast(BackgroundGetDeviceDataService.this.getApplicationContext());
                Dbug.i(tag,"-------------onUploadFinish-----");
            }
        });
    }

    /**
     * 在app退到后台的时候，连接设备获取传感器数据并上传
     */
    private void connnectToGetDeviceData_Background(){

        Dbug.i(tag, "--------------connnectToGetDeviceData_NOBackground---");
        //判断是否已经连接设备，如果连接设备可以直接去数据
        if(mApplication.getIsOffLineMode()&&isGetingDeviceData == false){
            //联网
            String ssid = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString(CURRENT_SSID,null);
            String password = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString(CURRENT_PWD, "12345678");
            Dbug.i(tag,"----------ssid:" + ssid + ",password:" + password);
            if(ssid != null)
                connectDevice(ssid, password);
        }else{
            //sendCommandToService(IConstant.SERVICE_CMD_INIT_SOCKET);
            //连接好了，可以直接取数据
            if(isGetingDeviceData)
                return;
            if(mHandler != null){
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        getDevicesData();
                    }
                });
            }else{
                mHandler = new Handler();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        getDevicesData();
                    }
                });
            }

        }
    }

    /**
     * 在app打开的情况下上传或下载
     */
    private void connnectToGetDeviceData_noBackground(){
        Dbug.i(tag,"--------------connnectToGetDeviceData_NOBackground---");
        //判断是否已经连接设备，如果连接设备可以直接去数据
        String device_id = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("device_id",null);
        if(device_id == null)
            return;
        DVRCarManager.getInstance().initRegisterInfo(device_id, "chainway", this.getApplicationContext());
        if(mApplication.getIsOffLineMode()&&isGetingDeviceData == false){
            //联网
            isGetingDeviceData = true;
            DVRCarManager.getInstance().setIsUploading(true);
            DVRCarManager.getInstance().uploadHTTPFiles(new DVRCSVUtil.OnUploadStrokeListener() {
                @Override
                public void onUploadInit(int errorcode, boolean is_success) {
                    Dbug.i(tag, "-------------onUploadInit-----issuccess:" + is_success);
                    if (!is_success) {
                        isGetingDeviceData = false;
                        DVRCarManager.getInstance().setIsUploading(false);
                    }
                }

                @Override
                public void onUploadFailed(int i,String filename, int i1, int i2) {
                    Dbug.i(tag, "-------------onUploadFailed-----errorcode:" + i);
                }

                @Override
                public void onUploadPrograss(String s, int i, int i1) {
                    Dbug.i(tag, "-------------onUploadPrograss----filename:" + s + "----count:" + i + "----index:" + i1);
                }

                @Override
                public void onUploadAllSuccess(int i) {
                    Dbug.i(tag, "-------------onUploadAllSuccess-----");
                    isGetingDeviceData = false;
                    DVRCarManager.getInstance().setIsUploading(false);
                    PreferencesHelper.putLongValue(BackgroundGetDeviceDataService.this.getApplicationContext(), "upload_cardev_time", System.currentTimeMillis());
                }

                @Override
                public void onUploadFinish() {
                    isGetingDeviceData = false;
                    DVRCarManager.getInstance().setIsUploading(false);
                    DVRCarManager.getInstance().sendFinishUploadBroadcast(BackgroundGetDeviceDataService.this.getApplicationContext());
                    Dbug.i(tag, "-------------onUploadFinish-----");
                }
            });

        }else if(mApplication.getIsOffLineMode() == false&&isGetingDeviceData == false){
            isGetingDeviceData = true;
            DVRCarManager.getInstance().setIsDownloading(true);
            DVRCarManager.getInstance().downloadFTPFiles("192.168.1.1", 21, "FTPX", "12345678", device_id, new OnDownloadFTPFileListener() {
                @Override
                public void onDownloadInit(int errorcode, boolean issuccess) {
                    if (!issuccess) {
                        isGetingDeviceData = false;
                        DVRCarManager.getInstance().setIsDownloading(false);
                    }
                    Dbug.i(tag, "-------------onDownloadInit-----");
                }

                @Override
                public void onDownloadAllSuccess(int i) {
                    Dbug.i(tag, "-------------onDownloadAllSuccess-----");
                    DVRCarManager.getInstance().setIsDownloading(false);
                    PreferencesHelper.putLongValue(BackgroundGetDeviceDataService.this.getApplicationContext(), "download_cardev_time", System.currentTimeMillis());
                    isGetingDeviceData = false;
                }

                @Override
                public void onDownloadFinish() {
                    DVRCarManager.getInstance().setIsDownloading(false);
                    DVRCarManager.getInstance().sendFinishDownloadBroadcast(BackgroundGetDeviceDataService.this.getApplicationContext());
                    isGetingDeviceData = false;
                    Dbug.i(tag, "-------------onDownloadFinish-----");
                }

                @Override
                public void onDownloadFailed(int i, int i1, int i2) {
                    Dbug.i(tag, "-------------onDownloadFailed-----");
                }

                @Override
                public void onDownloadPrograss(String s, int i, int i1) {
                    Dbug.i(tag, "-------------onDownloadPrograss----filename:" + s + "----count:" + i + "----index:" + i1);
                }
            });
        }
    }
    /**
     *
     * 连接设备热点
     * @param ssid 名称
     * @param password 密码
     */
    public void connectDevice(String ssid, String password) {

        Dbug.i(tag, "-------------connectDevice----------");
        /**Check if Wi-Fi enable */
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            return;
        }

        if (TextUtils.isEmpty(ssid)) {
            Dbug.i(tag, "SSID is null");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Dbug.i(tag, "PWD is null");
            password = "0";
        }

        mWifiHelper = WifiHelper.getInstance(this.getApplicationContext());
        if (mWifiHelper != null&&isExistWiFi(ssid)) {
            isIniting = true;
            if (password.equals("0")) {
                Dbug.i(tag, "=======connectDevice=====SSID=" + ssid + ", password=" + WifiHelper.WifiCipherType.NONE);
                mWifiHelper.addNetWorkAndConnect(ssid, password, WifiHelper.WifiCipherType.NONE);
            } else {
                Dbug.i(tag, "=======connectDevice=====SSID=" + ssid + ", password=" + password);
                mWifiHelper.addNetWorkAndConnect(ssid, password, WifiHelper.WifiCipherType.WPA);
            }
        }else if(mWifiHelper == null){
            Dbug.i(tag, "---------mWifiHelper:null-----");
        }
    }


    /**
     * 断开设备wifi热点，连接外网
     */
    public void disconnectDevice() {

        Dbug.d(tag, "disconnectDevice-----------------");
        mApplication.setIsNeedReconnect(false);
        mApplication.setIsOffLineMode(true);
        mApplication.setRealCamera(false);
        //CommandHub.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_DISABLE_DEVICE_WIFI);
        ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_DISABLE_DEVICE_WIFI, ARGS_DISABLE_DEVICE_WIFI);
        if(CommunicationService.getIsInitService()){
            sendCommandToService(IConstant.SERVICE_CMD_CLOSE_SOCKET);
            Dbug.i("CommunicationService", "-----------SERVICE_CMD_CLOSE_SOCKET----" + "disconnectDevice");
        }

        removeCurrentNetwork();

        mWifiHelper.connectOtherWifi(IConstant.WIFI_PREFIX);
    }


    /**
     * 移除当前网络
     */
    protected void removeCurrentNetwork() {

        Dbug.i(tag, "==========removeCurrentNetwork");

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null || wifiInfo.getSSID() == null) {
            Dbug.e(tag, "-=-=-=wifiInfo is null or  wifiInfo.getSSID() is null");
            return;
        }
        //int index = WIFI_PREFIX.lastIndexOf(",");
        //String str1 = WIFI_PREFIX.substring(0, index);
        //String str2 = WIFI_PREFIX.substring(index + 1, WIFI_PREFIX.length());
        boolean flag = false;
        String[] s = WIFI_PREFIX.split(",");
        for(int i = 0;i < s.length;i++){
            if(wifiInfo.getSSID().startsWith(s[i])){
                flag = true;
                break;
            }else{
                continue;
            }
        }
        if (flag||wifiInfo.getSSID().contains("168")) {
            Dbug.w(tag, "wifiInfo.getNetworkId:" + wifiInfo.getNetworkId());
//            wifiManager.disableNetwork(wifiInfo.getNetworkId());
//            wifiManager.disconnect();
//            wifiManager.removeNetwork(wifiInfo.getNetworkId());
//            wifiManager.saveConfiguration();
            mWifiHelper.remoteNetWork(wifiInfo.getNetworkId());
        }
    }

    /**
     * 判断当前wifi的ssid是否存在
     * @param ssid
     * @return
     */
    private boolean isExistWiFi(String ssid){
        boolean isexit = false;
        final List<ScanResult> list = mWifiHelper.getSpecifiedSSIDList(WIFI_PREFIX);
        for(int i = 0; i < list.size();i++){
            if(list.get(i).SSID.equals(ssid)){
                isexit = true;
                break;
            }
        }
        return isexit;
    }

    /**
     * 发送命令给设备呢，启动或断开
     * @param cmd
     */
    public void sendCommandToService(int cmd) {
        Intent intent = new Intent(this, CommunicationService.class);
        Dbug.i("CommunicationService","-------------sendCommandToService----id:" + cmd);
        intent.putExtra(IConstant.SERVICE_CMD, cmd);
        startService(intent);
    }

    /**
     * 注册监听，包括wifi监听，热点wifi连接状态监听
     */
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter(IAction.ACTION_DEVICE_WIFI_DISABLED);
        intentFilter.addAction(IAction.ACTION_SDCARD_STATE);
        intentFilter.addAction(ACTION_DEVICE_CONNECTION_ERROR);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(IAction.ACTION_REJECT_CONNECTION);
        intentFilter.addAction(ACTION_REQUEST_UI_DESCRIPTION);
        intentFilter.addAction(ACTION_QUIT_APP);
        intentFilter.addAction(ACTION_GET_ENCRYPTION_ERROR);
        registerReceiver(mReceiver, intentFilter);
    }


    /**
     * 状态监听器
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTION_DEVICE_WIFI_DISABLED:
                    mApplication.setErrorFlag(true);
                    if(mApplication.getIsOffLineMode() == false)
                    {
                        mApplication.setIsOffLineMode(true);
                        mApplication.setRealCamera(false);
                    }
                    break;
                case ACTION_SDCARD_STATE:
                    break;
                case ACTION_DEVICE_CONNECTION_ERROR:
                    int errorType = intent.getIntExtra(KEY_DEVICE_CONNECTION_ERROR, -1);

                    Dbug.i(tag, "==errorType==" + errorType);
                    switch (errorType) {
                        case CommandHub.ERROR_CONNECTION_EXCEPTION:
                            mApplication.setErrorFlag(true);
                            break;
                        case CommandHub.ERROR_CONNECTION_TIMEOUT:
                            mApplication.setErrorFlag(true);
                            break;
                    }
                    if(mApplication.getIsOffLineMode() == false)
                    {
                        mApplication.setIsOffLineMode(true);
                        mApplication.setRealCamera(false);
                    }
                    break;
                case ACTION_REJECT_CONNECTION:
                    break;
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    if (wifiInfo == null || TextUtils.isEmpty(wifiInfo.getSSID())) {
                        Dbug.e(tag, "SSID is null");
                        //connectDevice();
                        if(mApplication.getIsOffLineMode() == false)
                        {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                            isIniting = false;
                        }
                        //connectError();
                        return;
                    }
                    final String prefixSSID = wifiInfo.getSSID().replace("\"", "");
                    Dbug.i(tag, "Current prefixSSID=====" + prefixSSID + ", getNetworkId==" + wifiInfo.getNetworkId());

                    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    Dbug.e(tag, "Is connected: " + info.isConnected() + ", isNeedReconnection="  + ",isReadyToConnect="
                            + "State:" + info.getState());
                    if (info.isConnected() && wifiInfo.getNetworkId() >= 0 && (prefixSSID.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID.contains(WIFI_PREFIX_168))) {

                        Dbug.e(tag, "Connect device wifi success, now init=====");
//                        init();
                        String dev_mac_address = wifiInfo.getMacAddress();
                        PreferencesHelper.putStringValue(context, "ter_id", dev_mac_address);
                        //sendCommandToService(IConstant.SERVICE_CMD_INIT_SOCKET);
                        if(AppUtil.isAppInBackground(BackgroundGetDeviceDataService.this)){
                            sendCommandToService(IConstant.SERVICE_CMD_INIT_SOCKET);
                        }
                        isIniting = false;
                        Dbug.e("connected---", "完成连接");
                    } else if(info.getState().equals(NetworkInfo.State.CONNECTING)&&prefixSSID.startsWith(WIFI_PREFIX)){
                        //连接中;
                        Dbug.e("connecting---", "连接中");
                    }else if(info.getState().equals(NetworkInfo.State.UNKNOWN)&&(prefixSSID.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID.contains(WIFI_PREFIX_168))){
                        Dbug.e("connected---nuknown", "未知错误");
                        isIniting = false;
                        if(mApplication.getIsOffLineMode() == false)
                        {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                        }
                    }
                    else if((info.getState().equals(NetworkInfo.State.DISCONNECTED))
                            &&(prefixSSID.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID.contains(WIFI_PREFIX_168))&&wifiInfo.getNetworkId() < 0
                            &&(info.getDetailedState().equals(NetworkInfo.DetailedState.DISCONNECTED))) {
                        Dbug.e("disconnected---", "完成失败,密码错误");
                        isIniting = false;
                        //if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                        //   mNotifyDialog.dismiss();
                        //}
                        //disconnectDevice();
                        //showToast("密码错误，请重新连接");


                    }else if(info.getState().equals(NetworkInfo.State.SUSPENDED)
                            &&(prefixSSID.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID.startsWith(WIFI_PREFIX_CARDVR) || prefixSSID.contains(WIFI_PREFIX_168))){
                        Dbug.e("SUSPENDED---","网络存在疑问");
                        isIniting = false;
                        if(mApplication.getIsOffLineMode() == false)
                        {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                        }
                    }else{
                        isIniting = false;
                        if(mApplication.getIsOffLineMode() == false)
                        {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                        }
                    }
                    break;
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    ConnectivityManager mConnectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    WifiManager wifiManager1 = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo11 = wifiManager1.getConnectionInfo();
                    String prefixSSID1 = "";
                    if(wifiInfo11 != null)
                        prefixSSID1 = wifiInfo11.getSSID().replace("\"", "");
                    NetworkInfo wifiInfo1 = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    if(wifiInfo1 != null&&wifiInfo11 != null &&(prefixSSID1.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID1.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID1.contains(WIFI_PREFIX_168))&&TextUtils.isEmpty(wifiInfo11.getSSID()) == false)
                    {
                        //do nothing
                    }else
                    {
                        Dbug.i(tag,"--------------CONNECTIVITY_ACTION---------网络存在疑问");
                        if(mApplication.getIsOffLineMode() == false)
                        {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                        }
                    }
                    break;
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                    SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
                    int supplicantError = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
//                    Dbug.d(tag, "supplicantError=" + supplicantError + ", state=" + state);
                    if (SupplicantState.DISCONNECTED.equals(state) && supplicantError == WifiManager.ERROR_AUTHENTICATING ) {

                        if(mApplication.getIsOffLineMode() == false)
                        {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                        }

                        Dbug.i(tag,"-----------------password error---------");
                    }

                    break;
                case ACTION_REQUEST_UI_DESCRIPTION:
                    Dbug.i(tag, "-----------------ACTION_REQUEST_UI_DESCRIPTION---------");
                    mApplication.setIsOffLineMode(false);
                    mApplication.setIsFirstReadData(true);
                    mApplication.setIsNeedReconnect(false);

                    if(AppUtil.isAppInBackground(BackgroundGetDeviceDataService.this)){
                        if(mHandler != null){
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    getDevicesData();
                                }
                            });
                        }else{
                            mHandler = new Handler();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    getDevicesData();
                                }
                            });
                        }
                    }
                    break;
                case ACTION_GET_ENCRYPTION_ERROR:
                    break;
                case ACTION_QUIT_APP:
                    break;
            }
        }
    };
}
